package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    //营业额统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDates.add(begin);
        }

        List<Double> counts = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            Double count = orderMapper.turnoverStatistics(LocalDateTime.of(localDate, LocalTime.MIN),LocalDateTime.of(localDate, LocalTime.MAX));
            count=count==null? 0.0 :count;
            counts.add(count);
        }


        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(localDates,","))
                .turnoverList(StringUtils.join(counts,","))
                .build();
    }

    //用户统计
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDates.add(begin);
        }

        List<Integer> userCount = new ArrayList<>();
        List<Integer> newUserCount = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            Map userMap = new HashMap<>();
            userMap.put("end",LocalDateTime.of(localDate, LocalTime.MAX));

            Map newUserMap = new HashMap<>();
            newUserMap.put("begin",LocalDateTime.of(localDate, LocalTime.MIN));
            newUserMap.put("end",LocalDateTime.of(localDate, LocalTime.MAX));
            Integer user = userMapper.userStatistics(userMap);
            Integer newUser = userMapper.userStatistics(newUserMap);
            user=user==null? 0 :user;
            newUser=newUser==null? 0 :newUser;
            userCount.add(user);
            newUserCount.add(newUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(localDates,","))
                .totalUserList(StringUtils.join(userCount,","))
                .newUserList(StringUtils.join(newUserCount,","))
                .build();
    }

    //订单统计
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDates.add(begin);
        }

        List<Integer> orderCountByDay = new ArrayList<>();
        List<Integer> validOrderCountByDay = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            Map orderMap = new HashMap<>();
            orderMap.put("begin",LocalDateTime.of(localDate, LocalTime.MIN));
            orderMap.put("end",LocalDateTime.of(localDate, LocalTime.MAX));

            Map validOrderMap = new HashMap<>();
            validOrderMap.put("begin",LocalDateTime.of(localDate, LocalTime.MIN));
            validOrderMap.put("end",LocalDateTime.of(localDate, LocalTime.MAX));
            validOrderMap.put("status", Orders.COMPLETED);
            Integer orderByDay = orderMapper.ordersStatistics(orderMap);
            Integer validOrderByDay = orderMapper.ordersStatistics(validOrderMap);
            orderByDay=orderByDay==null? 0 :orderByDay;
            validOrderByDay=validOrderByDay==null? 0 :validOrderByDay;
            orderCountByDay.add(orderByDay);
            validOrderCountByDay.add(validOrderByDay);
        }

        Map totalOrderCountMap = new HashMap<>();
        Integer totalOrderCount = orderMapper.ordersStatistics(totalOrderCountMap);

        Map validOrderCountMap = new HashMap<>();
        validOrderCountMap.put("status",Orders.COMPLETED);
        Integer validOrderCount = orderMapper.ordersStatistics(validOrderCountMap);

        Double orderCompletionRate =  validOrderCount/(double)totalOrderCount;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(localDates,","))
                .orderCountList(StringUtils.join(orderCountByDay,","))
                .validOrderCountList(StringUtils.join(validOrderCountByDay,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    //查询销量排名top10
    @Override
    public SalesTop10ReportVO saleTop10(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        Map map = new HashMap<>();
        map.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("end", LocalDateTime.of(end, LocalTime.MAX));

        List<GoodsSalesDTO> goodsSalesList = orderDetailMapper.saleCount(map);
        for (GoodsSalesDTO goodsSales : goodsSalesList) {
            nameList.add(goodsSales.getName());
            numberList.add(goodsSales.getNumber());
        }

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    //导出Excel报表接口
    @Override
    @Transactional
    public void exportExcel(HttpServletResponse response) {
        //查询最近三十天的数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workspaceService.businessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));

        //通过PIO将数据写入excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO business = workspaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(business.getTurnover());
                row.getCell(3).setCellValue(business.getValidOrderCount());
                row.getCell(4).setCellValue(business.getOrderCompletionRate());
                row.getCell(5).setCellValue(business.getUnitPrice());
                row.getCell(6).setCellValue(business.getNewUsers());

            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            excel.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
